<?php
$config['engagd_server'] = 'http://engagd.gobblerss.pommepause.com/';

if (isset($_GET['apml_engagd']) && $_GET['apml_engagd'] == 'pending') {
	engagd_processPending();
}

$apml_engagd_userId = null;
function engagd_getUserId() {
	global $config, $apml_engagd_userId;

	// Already fetched userId during this call.
	if ($apml_engagd_userId != null) {
		return $apml_engagd_userId;
	}

	// Already fetched userId during a previous call.
	global $link;
	if (!isset($link)) {
		$link = db_connect();
	}
	$result = mysql_query("SELECT value FROM variables WHERE name = 'apml_engagd_userId'", $link);
	if (mysql_errno()) {
		die("Can't load variables.value for userId: " . mysql_error() . "\n");
	}
	if (mysql_num_rows($result) == 1) {
		$apml_engagd_userId = mysql_result($result, 0, 'value');
		return $apml_engagd_userId;
	}

	// Fetch a new userId; none was found locally.
	glog("[APML] Fetching userId from ".$config['engagd_server'], FALSE);
	$local_url = substr($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'], 0, strrpos($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'], '/'));
	$url = $config['engagd_server'].'?getUserId=y&url='.urlencode($local_url);
	$result = get_web_page($url);
	if ($result === FALSE) {
		glog("Error fetching Engagd userId using $url.");
		return null;
	}
	if (strstr($result, 'ERROR:') !== FALSE) {
		glog("Error fetching Engagd userId using $url: ".substr($result, 6));
		return null;
	}
	mysql_query(sprintf("INSERT INTO variables (name,value) VALUES ('apml_engagd_userId','%s')", mysql_escape_string($result)), $link);
	if (mysql_errno()) {
		die("Can't save userId in variables: " . mysql_error() . "\n");
	}
	$apml_engagd_userId = $result;
	glog("[APML] Engagd userId '$apml_engagd_userId' saved locally.", FALSE);

	// Since it's the first time we call this function, we need to generate a new profile from already opened/starred articles.
	engagd_dbmigration();

	return $apml_engagd_userId;
}

function engagd_processPending() {
	global $apml_engagd_userId, $link;
	$apml_engagd_userId = engagd_getUserId();

	// Process max 10 pending transactions each time.
	$articles_query = "SELECT id, link FROM articles WHERE engagd = 'pending' ORDER BY id LIMIT 10";
	$result = mysql_query($articles_query, $link)
		or die("ERROR:Can't load articles: " . mysql_error() . "\n");

	if (mysql_num_rows($result) == 0) {
		die('DONE');
	}

	// This could take a while!
	// Allow 4 seconds per article; it shouldn't take much more than 1... Plus 30 seconds sleep between calls.
	$sleep_between_calls = 30;
	set_time_limit($numRows * (4 + $sleep_between_calls));

	while ($article = mysql_fetch_array($result)) {
		engagd_addPageToProfile($apml_engagd_userId, $article['link'], $article['id']);
		sleep($sleep_between_calls);
	}

	die('CONTINUE');
}

function engagd_addPageToProfile($apml_engagd_userId, $url, $id) {
	global $config, $link;

	// Make sure this article APML transaction is really pending before continuing.
	$articles_query = "SELECT * FROM articles WHERE id = $id AND engagd = 'pending'";
	$result = mysql_query($articles_query, $link)
		or die("Can't load articles: " . mysql_error() . "\n");
	if (mysql_num_rows($result) == 0) {
		return;
	}

	glog("[APML] Adding $url to Engagd profile for $apml_engagd_userId (engagd_addPageToProfile).", FALSE);
	$result = get_web_page($config['engagd_server'].'?addPageToProfile=y&userId='.urlencode($apml_engagd_userId).'&url='.urlencode($url));
	glog("[APML] Result of adding $url to Engagd profile for $apml_engagd_userId (engagd_addPageToProfile): '$result'", FALSE);
	if (strstr($result, "ERROR:HTTP:403:") !== FALSE) {
		// This means the APML provider, Engagd, asked us to wait before calling the API again; let's wait (1h).
		die('WAIT:3600');
	} else if (strstr($result, "ERROR:CURL:28:") !== FALSE) {
		// Timed out; let's try again later (in 30 minutes)...
		die('WAIT:1800');
	} else if (strstr($result, "ERROR") !== FALSE) {
		die($result);
	} else {
		if (!isset($link)) {
			$link = db_connect();
		}
		$articles_query = "UPDATE articles SET engagd = 'done' WHERE id = $id";
		mysql_query($articles_query, $link)
			or die("ERROR:Can't update articles, engagd = 'done': " . mysql_error() . "\n");
	}
}

function engagd_getProfile($apml_engagd_userId) {
	global $config;
	glog("[APML] Fetching Engagd profile for $apml_engagd_userId (engagd_getProfile).", FALSE);
	echo get_web_page($config['engagd_server'].'?getProfile=y&userId='.urlencode($apml_engagd_userId));
}

function engagd_dbmigration() {
	global $link;
	if (!isset($link)) {
		$link = db_connect();
	}
	/* DB Migration for Engagd APML : add 'engagd' column to articles table */
	$res = mysql_query("DESCRIBE articles", $link)
		or die("Failed DESCRIBE articles: " . mysql_error() . "\n");
	$need_update = true;
	while ($row = mysql_fetch_array($res)) {
		if ($row['Field'] == 'engagd') {
			$need_update = false;
			break;
		}
	}
	if ($need_update) {
		mysql_query("ALTER TABLE articles ADD engagd SET('pending','done'), ADD INDEX engagd (engagd,state)", $link)
			or die("Failed ADD engagd column for DB Migration APML: " . mysql_error() . "\n");
	}
	/* Mark past flagged articles 'pending' */
	$apml_pending_query = "UPDATE articles SET engagd='pending' WHERE engagd IS NULL AND (state LIKE '%starred%' OR state LIKE '%unread%' OR state LIKE '%open%')";
	mysql_query($apml_pending_query, $link)
		or die("Can't update articles, engagd = 'pending': " . mysql_error() . "\n");
}
?>
